package com.hatic.test;

import java.util.List;

import java.util.Map;

import org.jxstar.dao.DaoParam;
import org.jxstar.service.BusinessObject;
import org.jxstar.util.DateUtil;
import org.jxstar.util.key.KeyCreator;

/**
 * 处理用户授权的类
 * 给没有授权的用户统一设置部门权限，默认值为本部门
 * @author Thinkpad
 *
 */
public class UserDataBO  extends BusinessObject{
	private static final long serialVersionUID = 1L;
	
	public String updateUserdata(){
		List<Map<String, String>> list = queryUser(); 
		
		for(int i = 0, n = list.size(); i < n; i++){      
			Map<String, String> mpData = list.get(i);
			String userId = mpData.get("user_id");
			String deptId = mpData.get("dept_id");
			Map<String, String> ppData = queryDept(deptId);
			String deptName = ppData.get("dept_name");
			
			if(!updateData(userId,deptId,deptName)){
				setMessage("更新用户授权出错！");
				return _returnFaild;
			}
		}
		
		return _returnSuccess;
	}
	/**
	 * 向用户权限表中插入记录
	 * @param userId
	 * @param deptId
	 * @param deptName
	 * @return
	 */
	private boolean updateData(String userId, String deptId, String deptName){
		String sql ="insert into sys_user_data(USER_DATA_ID,USER_ID,DTYPE_ID,"+
						"ADD_USERID,ADD_DATE,MODIFY_USERID,MODIFY_DATE,DTYPE_DATA,HAS_SUB,DISPLAY)"+
						"values(?,?,?,?,?,?,?,?,?,?)" ;
		DaoParam param = _dao.createParam(sql);
		
		String userdataID = KeyCreator.getInstance().createKey("sys_user_data");
		param.addStringValue(userdataID);
		param.addStringValue(userId);
		param.addStringValue("jxstar1");
		param.addStringValue("administrator");
		param.addDateValue(DateUtil.getToday());
		param.addStringValue("administrator");
		param.addDateValue(DateUtil.getToday());
		param.addStringValue(deptId);
		param.addStringValue("1");
		param.addStringValue(deptName);
		
		if (!_dao.update(param)) {
			_log.showError("授权出错！");
			return false;
		}
		
		return true;
	}
	
	/**
	 * 查找还没有授权的用户
	 * @return
	 */
	private List<Map<String,String>> queryUser() {
		String sql = "select * from sys_user where user_id not in ( select user_id from sys_user_data )  ";
		DaoParam param = _dao.createParam(sql);
		
		return _dao.query(param);
	}
	/**
	 * 查找部门ID和部门名称
	 * @param deptId
	 * @return
	 */
	private Map<String,String> queryDept(String deptId) {
		String sql = "select dept_id, dept_name from sys_dept where dept_id = ?";
		DaoParam param = _dao.createParam(sql);
		param.addStringValue(deptId);
		
		return _dao.queryMap(param);
	}
}
